package com.demo.lottery.probability;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;


/**
 * @author wangfengchen
 * 抽奖类
 */
public class Lottery {
  // 奖品列表
  private List<Prize> prizes;
  // 总概率
  private double totalProbability;

  // 构造函数
  public Lottery(List<Prize> prizes) {
    this.prizes = new ArrayList<>(prizes);
    calculateTotalProbability();
    calculateCumulativeProbabilities();
  }

  /**
   * 计算总概率
   * 抽奖初始化时，先计算总概率
   */
  private void calculateTotalProbability() {
    totalProbability = 0;
    for (Prize prize : prizes) {
      totalProbability += prize.getProbability();
    }
  }

  /**
   * 计算每个奖品的累计概率
   * 抽奖初始化时，计算好总概率后，计算每个奖品的累计概率
   */
  private void calculateCumulativeProbabilities() {
    double cumulativeProbability = 0;
    for (Prize prize : prizes) {
      cumulativeProbability += prize.getProbability();
      prize.setCumulativeProbability(cumulativeProbability);
    }
  }

  /**
   * 抽奖
   * 通过随机数*总概率算数当前中将概率，循环奖品列表，
   * 如果当前随机数小于等于当前奖品的累计概率（随机数在哪个区间），则返回当前奖品
   *
   * @return
   */
  public Prize draw() {
    Random random = new Random();
    double randomNumber = random.nextDouble() * totalProbability;
    for (Prize prize : prizes) {
      if (randomNumber <= prize.getCumulativeProbability()) {
        return prize;
      }
    }
    return prizes.get(prizes.size() - 1);
  }

  /**
   * 测试中奖概率比例
   * @param args
   */
  public static void main(String[] args) {
    List<Prize> prizes = Arrays.asList(
        new Prize("一等奖", 0.1),
        new Prize("二等奖", 0.3),
        new Prize("谢谢参与", 0.6)
    );

    int[] result = new int[prizes.size()];
    Lottery lottery = new Lottery(prizes);
    for (int i = 0; i < 10000; i++) {
      Prize prize = lottery.draw();
      result[prizes.indexOf(prize)]++;
    }
    System.out.println("一等奖：" + result[0]);
    System.out.println("二等奖：" + result[1]);
    System.out.println("谢谢参与：" + result[2]);
  }

}